import { ContentType, requestConfig, request } from './http';

// 高德「地点提示」接口（tips）响应 TypeScript 定义
// 适用于 https://restapi.amap.com/v3/assistant/inputtips 等

/** 单条提示项 */
export interface AmapTip {
  id: string; // POI ID
  name: string; // 名称
  district: string; // 所在行政区拼接串（如 BeijingHaidian）
  adcode: string; // 区域编码
  location: string; // "lng,lat"
  address: string; // 详细地址
  typecode: string; // POI 类型码
  city: string[]; // 兼容字段，返回为空数组
}

/** 高德外层响应 */
export interface AmapTipsProtocol {
  status: string; // "1" 成功
  info: string; // "OK"
  infocode: string; // "10000"
  count: string; // 结果条数
  tips: AmapTip[];
}

/*
 * @param language 语言
 * @param keywords 关键字
 * @param city 城市
 * @returns Promise<Protocol<Tip[]>>
 * @description 输入提示
 */
export function amapTips(language: string, keywords: string, city: string): Promise<AmapTipsProtocol> {
  return request.get<AmapTipsProtocol>(`/cloud/amap-api/v3/assistant/inputtips`, { language, keywords, city });
}

/**
 * 地址组件
 */
export interface AddressComponent {
  longText: string;
  shortText: string;
  types: string[];
  languageCode: string; // "en" | "zh-Latn" | "zh" ...
}

/**
 * 经纬度
 */
export interface LatLng {
  latitude: number;
  longitude: number;
}

/**
 * 展示名称（多语言）
 */
export interface DisplayName {
  text: string;
  languageCode: string;
}

/**
 * Google Place Detail 响应主体
 * （对应请求：GET /v1/places/{placeId}）
 */
export interface GooglePlace {
  id: string;
  name: string;
  formattedAddress: string;
  addressComponents: AddressComponent[];
  location: LatLng;
  adrFormatAddress: string; // 带 HTML 转义的地址
  displayName: DisplayName;
  postalAddress: any; // 如需更细字段可再扩展
}

// 定义获取邮政编码的函数
export function findComponents(place: GooglePlace, types: string[]): string | undefined {
  const component = place.addressComponents.find((e) => {
    return types.every((t) => {
      if (e.types) {
        return e.types.includes(t);
      }
      return false;
    });
  });
  // 存在则返回 longText，否则返回 undefined
  return component?.longText?.replace(/\s+/g, '').toLowerCase();
}

export interface PlacesSearchResult {
  places: GooglePlace[];
}
export function placesSearch(query: string, language: string): Promise<PlacesSearchResult> {
  return request.post<PlacesSearchResult>(
    `/cloud/google-places/v1/places:searchText`,
    {
      textQuery: query,
      languageCode: language,
      // includedType: 'tourist_attraction',
    },
    requestConfig({
      ...ContentType.JSON,
      'X-Goog-FieldMask':
        'places.id,places.name,places.addressComponents,places.location,places.displayName,places.formattedAddress',
    })
  );
}
